package org.example.test1;

import org.apache.zookeeper.*;

import java.io.IOException;

public class DistributeServer {
    private String connectString = "47.108.48.236:2182";
    private int sessionTimeout = 300000;
    private ZooKeeper zooKeeper;
    private String path = "/server";

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DistributeServer server = new DistributeServer();
        // 与 zookeeper 建立连接
        server.getConnection();
        // 创建服务器临时节点
        String node = server.create("host1");
        System.out.println(node + " is online...");
        // 处理业务逻辑
        server.business();
    }

    private void business() throws InterruptedException {
        Thread.sleep(Integer.MAX_VALUE);
    }

    private String create(String host) throws InterruptedException, KeeperException {
         return zooKeeper.create(path + "/" + host, host.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
    }

    private void getConnection() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}
